package org.kreedx.view.manager;


import java.util.ArrayList;

public class TextManager {
    private String text;

    private ArrayList<String> pageContent = new ArrayList<>();
    private int lineNum;
    private int wordNum;

    public static TextManager create(String text,int lineNum,int wordNum){
        TextManager textManager = new TextManager();
        textManager.text = text;
        textManager.lineNum = lineNum;
        textManager.wordNum = wordNum;
        textManager.init();
        return textManager;
    }

    private void init() {

        String[] temps = text.split("\n");

        int needLine = lineNum; //下一页需要的行数
        StringBuilder tempPage = new StringBuilder();//下一页内容
        for (String temp : temps) {
            int num = temp.length();
            while (num > (needLine-1) * wordNum) {


                int start = temp.length() - num;
                int end = start + needLine * wordNum;
                if(end > temp.length()){
                    end = temp.length();
                    num = 0;
                }else {
                    num -= needLine * wordNum;
                }

                if(!tempPage.toString().equals("")){
                    tempPage.append("\n");
                }
                tempPage.append(temp.substring(start,end));

                pageContent.add(tempPage.toString());
                needLine = lineNum;
                tempPage = new StringBuilder();
            }

            if ( num > 0) {
                int line = num / wordNum + 1;
                needLine -= line;
                if(!tempPage.toString().equals("")){
                    tempPage.append("\n");
                }
                tempPage.append(temp.substring(temp.length() - num, temp.length()));
            }

            if(temp.equals(temps[temps.length - 1])){
                pageContent.add(tempPage.toString());
            }
        }
    }

    public String getPage(int page){
        if(page >= pageContent.size())return "";
        return pageContent.get(page-1);
    }

    public int getPageNum(){
        return pageContent.size();
    }
}
